<?php
/**
 * Created by PhpStorm.
 * User: wangjiangtao
 * Date: 2022/5/25
 * Time: 15:43
 */

namespace App\Model;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class Activity extends BaseModel
{
    protected $connection = 'api';
    protected $giftLibraryTable = 'gift_library';
    protected $userTable = 'user';

    protected $activityConn = 'activity';
    protected $gs_stat_table = 'giftstar_statistics';
    protected $i_dayStatTable = 'invite202307_day_statistics';
    protected $invite202310_send_log_table = 'invite202310_send_log';//邀请三期
    protected $fc_event_table = 'familycompetition_event';
    protected $fc_stat_table = 'familycompetition_statistics';
    protected $fc_stat_shop_table = 'familycompetition_shop_statistics';

    public function getGiftstarConfigAdd($data){
        $res = curl_request(getKkaudioActivityUrl() . '/inner/giftstar/config/add', $data, 'json', 'POST');
        if(isset($res['code']) && $res['code']==0) {
            return 1;
        }else{
            return [
                'code' => 50000,
                'msg' => empty($res['msg']) ? '失败' : $res['msg'],
            ];
        }
    }

    public function getGiftstarConfigDelete($param){
        $data = [
            'id'   => $param['id'],
        ];
        $res = curl_request(getKkaudioActivityUrl() . '/inner/giftstar/config/delete', $data, 'urlencoded', 'GET');
        if(isset($res['code']) && $res['code']==0) {
            return 1;
        }else{
            return [
                'code' => 50000,
                'msg' => empty($res['msg']) ? '失败' : $res['msg'],
            ];
        }
    }

    public function getGiftstarConfigList($param){
        $data = [
            'week'   => $param['week'],
            'page'   => $param['page'],
            'limit'   => $param['limit'],
        ];
        $res = curl_request(getKkaudioActivityUrl() . '/inner/giftstar/config/list', $data, 'urlencoded', 'GET');
        if(isset($res['code']) && $res['code']==0) {
            return $res['data'];
        }else{
            return [];
        }
    }

    public function getGiftstarRewardList($param){
        $data = [
            'id'   => $param['id'],
        ];
        $res = curl_request(getKkaudioActivityUrl() . '/inner/giftstar/reward/list', $data, 'urlencoded', 'GET');
        if(isset($res['code']) && $res['code']==0) {
            return $res['data'];
        }else{
            return [];

        }
    }

    //获取周星榜统计列表
    public function getGiftstarStatisticsList(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');

        $query = DB::connection($this->activityConn)->table($this->gs_stat_table)->orderBy('id', 'desc');
        if(!empty($date_st)) {
            $date_st = date("Ymd", strtotime($date_st));
            $query = $query->where('ymd', '>=', $date_st);
        }
        if(!empty($date_ed)) {
            $date_ed = date("Ymd", strtotime($date_ed));
            $query = $query->where('ymd', '<=', $date_ed);
        }

        $result = $query->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);
        foreach($result['data'] as $key=>$val) {
            $giftInfo = DB::connection($this->connection)->table($this->giftLibraryTable)->where('gift_id', $val['gift1'])->first();
            $giftInfo = objToArray($giftInfo);
            $val['giftName1'] = empty($giftInfo['name']) ? '' : $giftInfo['name'];
            $val['giftPrice1'] = empty($giftInfo['price']) ? 0 : $giftInfo['price'];

            $giftInfo = DB::connection($this->connection)->table($this->giftLibraryTable)->where('gift_id', $val['gift2'])->first();
            $giftInfo = objToArray($giftInfo);
            $val['giftName2'] = empty($giftInfo['name']) ? '' : $giftInfo['name'];
            $val['giftPrice2'] = empty($giftInfo['price']) ? 0 : $giftInfo['price'];

            $giftInfo = DB::connection($this->connection)->table($this->giftLibraryTable)->where('gift_id', $val['gift3'])->first();
            $giftInfo = objToArray($giftInfo);
            $val['giftName3'] = empty($giftInfo['name']) ? '' : $giftInfo['name'];
            $val['giftPrice3'] = empty($giftInfo['price']) ? 0 : $giftInfo['price'];

            $result['data'][$key] = $val;
        }

        return $result;
    }

    //邀请活动三期每日钻石分成用户明细
    public function getInvite202310DayDiamondList(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $invite_user_id = $request->input('invite_user_id');
        $query = DB::connection($this->activityConn)->table($this->invite202310_send_log_table);
        if(!empty($date_st)) {
            $date_st = strtotime(date("Ymd", strtotime($date_st)));
            $query = $query->where('date', '>=', $date_st);
        }
        if(!empty($date_ed)) {
            $date_ed = strtotime(date("Ymd", strtotime($date_ed)));
            $query = $query->where('date', '<=', $date_ed);
        }
        if(!empty($invite_user_id)) {
            $query = $query->where('user_id', $invite_user_id);
        }

        $list = $query->selectRaw('sum(send_diamon_value) as diamondNum, user_id, date')
            ->groupBy('date', 'user_id')
            ->orderBy('date', 'desc')
            ->get();
        $list = objToArray($list);

        $userList = [];
        if(!empty($list)) {
            $userIds = array_column($list, 'user_id');
            $userList = DB::connection($this->connection)->table($this->userTable)->whereIn('user_id', $userIds)->select('user_id', 'uuid', 'nickname')->get();
            $userList = objToArray($userList);
            $userList = array_column($userList, null, 'user_id');
        }

        foreach($list as $key=>$val) {
            $val['date'] = $val['date'];
            $val['invite_uuid'] = empty($userList[$val['user_id']]['uuid']) ? '' : $userList[$val['user_id']]['uuid'];
            $val['invite_nickname'] = empty($userList[$val['user_id']]['nickname']) ? '' : $userList[$val['user_id']]['nickname'];
            $val['jdNum'] = 0;

            $list[$key] = $val;
        }

        $result['list'] = $list;
        return $result;
    }
    //邀请活动每日用户邀请贡献明细
    public function getInvite202310DayStatList(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $invite_user_id = $request->input('invite_user_id');
        $user_id = $request->input('user_id');
        $user_nickname = $request->input('invite_nickname');
        $invite_code = $request->input('invite_code');
        $loginIp = $request->input('loginIp');
        //         todo 检测邀请码是否存在（将code转成user_id值）
        if(!empty($invite_code)){
            $inviteUserData = $this->getUserByCode($invite_code);
            if (empty($inviteUserData)) {
                return null;
            }
            $invite_uid_new = $inviteUserData['user_id'];
            $query = DB::connection($this->connection)->table($this->userTable);

        }elseif(!empty($loginIp)){
            $query = DB::connection($this->connection)->table($this->userTable.' as a')
                ->leftJoin('user_login_log'.' as b','a.user_id','=','b.user_id')
                ->where('a.invite_uid_new', '>', 0);
        }else{
            $query = DB::connection($this->connection)->table($this->userTable)->where('invite_uid_new', '>', 0);
        }
        if(!empty($date_st)) {
            $date_st = date("Ymd", strtotime($date_st));
            $query = $query->where('create_time', '>=', $date_st);
        }
        if(!empty($date_ed)) {
            $date_ed = date("Ymd", strtotime($date_ed));
            $query = $query->where('create_time', '<=', $date_ed);
        }
        if(!empty($invite_user_id)) {
            $query = $query->where('user_id', $invite_user_id);
        }
        if(!empty($user_id)) {
            $query = $query->where('invite_uid_new', $user_id);
        }
        if(!empty($user_nickname)) {
            $query = $query->where('nickname', $user_nickname);
        }
        if(!empty($invite_code)) {
            $query = $query->where('invite_uid_new', $invite_uid_new);
        }
        if(!empty($loginIp)) {
            $query = $query->where('b.ip', $loginIp);
        }

        $result = $query->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);
        $userList = [];
        if(!empty($result['data'])) {
            $userIds = array_merge(array_column($result['data'], 'user_id'), array_column($result['data'], 'invite_uid_new'));
            $userList = DB::connection($this->connection)->table($this->userTable)->whereIn('user_id', $userIds)->select('user_id', 'uuid', 'nickname','code','create_time')->get();
            $userList = objToArray($userList);
            $userList = array_column($userList, null, 'user_id');
            $loginIp=DB::connection($this->connection)->table('user_login_log')->whereIn('user_id', $userIds)->select('user_id', 'ip', 'os_name')->get();
            $loginIp = objToArray($loginIp);
            $loginIp = array_column($loginIp, null, 'user_id');

        }

        foreach($result['data'] as $key=>$val) {
            $val['invite_code'] = empty($userList[$val['invite_uid_new']]['code']) ? '' : $userList[$val['invite_uid_new']]['code'];
            $val['user_uuid'] = empty($userList[$val['invite_uid_new']]['uuid']) ? '' : $userList[$val['invite_uid_new']]['uuid'];
            $val['user_nickname'] = empty($userList[$val['invite_uid_new']]['nickname']) ? '' : $userList[$val['invite_uid_new']]['nickname'];
            $val['reg_time'] = empty($userList[$val['user_id']]['create_time']) ? '' : $userList[$val['user_id']]['create_time'];
            $val['invite_uuid'] = empty($userList[$val['user_id']]['uuid']) ? '' : $userList[$val['user_id']]['uuid'];
            $val['invite_nickname'] = empty($userList[$val['user_id']]['nickname']) ? '' : $userList[$val['user_id']]['nickname'];
            $val['loginIp'] = empty($loginIp[$val['user_id']]['ip']) ? '' : $loginIp[$val['user_id']]['ip'];
            $chongzhiAll=DB::connection($this->connection)->table('finance_recharge_order')->where('user_id', $val['user_id'])->where('status', 1)->selectRaw('sum(price) as diamondNum, user_id')->get();
            $chongzhiAll = objToArray($chongzhiAll);
            $diamondAll=DB::connection($this->connection)->table('finance_diamond_stream')->where('user_id', $val['user_id'])->where('diamond_value', '<', 0)->selectRaw('sum(diamond_value) as diamondAll, user_id')->get();
            $diamondAll = objToArray($diamondAll);
            $val['chongzhiAll'] = empty($chongzhiAll[0]['diamondNum']) ? '0' : $chongzhiAll[0]['diamondNum']/100;
            $val['diamondAll'] = empty($diamondAll[0]['diamondAll']) ? '0' : $diamondAll[0]['diamondAll'];
            $result['data'][$key] = $val;
        }
        return $result;

    }
    //邀请活动每日用户邀请贡献明细导出
    public function exportInvite202310DayStatList(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $invite_user_id = $request->input('invite_user_id');
        $user_id = $request->input('user_id');
        $user_nickname = $request->input('invite_nickname');
        $invite_code = $request->input('invite_code');
        $loginIp = $request->input('loginIp');

        if(!empty($invite_code)){
            $inviteUserData = $this->getUserByCode($invite_code);
            if (empty($inviteUserData)) {
                return null;
            }
            $invite_uid_new = $inviteUserData['user_id'];
            $query = DB::connection($this->connection)->table($this->userTable);

        }elseif(!empty($loginIp)){
            $query = DB::connection($this->connection)->table($this->userTable.' as a')
                ->leftJoin('user_login_log'.' as b','a.user_id','=','b.user_id')
                ->where('a.invite_uid_new', '>', 0);
        }else{
            $query = DB::connection($this->connection)->table($this->userTable)->where('invite_uid_new', '>', 0);
        }

        if(!empty($date_st)) {
            $date_st = date("Ymd", strtotime($date_st));
            $query = $query->where('create_time', '>=', $date_st);
        }
        if(!empty($date_ed)) {
            $date_ed = date("Ymd", strtotime($date_ed));
            $query = $query->where('create_time', '<=', $date_ed);
        }
        if(!empty($invite_user_id)) {
            $query = $query->where('user_id', $invite_user_id);
        }
        if(!empty($user_id)) {
            $query = $query->where('invite_uid_new', $user_id);
        }
        if(!empty($user_nickname)) {
            $query = $query->where('nickname', $user_nickname);
        }
        if(!empty($invite_code)) {
            $query = $query->where('invite_uid_new', $invite_uid_new);
        }
        if(!empty($loginIp)) {
            $query = $query->where('b.ip', $loginIp);
        }

        $list = $query->get();
        $list = objToArray($list);
        
        $userList = [];
        if(!empty($list)) {
            $userIds = array_merge(array_column($list, 'user_id'), array_column($list, 'invite_uid_new'));
            $userList = DB::connection($this->connection)->table($this->userTable)->whereIn('user_id', $userIds)->select('user_id', 'uuid', 'nickname','code','create_time')->get();
            $userList = objToArray($userList);
            $userList = array_column($userList, null, 'user_id');
            $loginIp=DB::connection($this->connection)->table('user_login_log')->whereIn('user_id', $userIds)->select('user_id', 'ip', 'os_name')->get();
            $loginIp = objToArray($loginIp);
            $loginIp = array_column($loginIp, null, 'user_id');
        }

        $data = [];
        foreach($list as $key=>$val) {
            $item = [];
            $item['invite_code'] = empty($userList[$val['invite_uid_new']]['code']) ? '' : $userList[$val['invite_uid_new']]['code'];
            $item['user_uuid'] = empty($userList[$val['invite_uid_new']]['uuid']) ? '' : $userList[$val['invite_uid_new']]['uuid'];
            $item['user_nickname'] = empty($userList[$val['invite_uid_new']]['nickname']) ? '' : $userList[$val['invite_uid_new']]['nickname'];
            $item['reg_time'] = empty($userList[$val['user_id']]['create_time']) ? '' : $userList[$val['user_id']]['create_time'];
            $item['invite_uuid'] = empty($userList[$val['user_id']]['uuid']) ? '' : $userList[$val['user_id']]['uuid'];
            $item['invite_nickname'] = empty($userList[$val['user_id']]['nickname']) ? '' : $userList[$val['user_id']]['nickname'];
            $item['loginIp'] = empty($loginIp[$val['user_id']]['ip']) ? '' : $loginIp[$val['user_id']]['ip'];
            
            $chongzhiAll=DB::connection($this->connection)->table('finance_recharge_order')->where('user_id', $val['user_id'])->where('status', 1)->selectRaw('sum(price) as diamondNum, user_id')->get();
            $chongzhiAll = objToArray($chongzhiAll);
            $diamondAll=DB::connection($this->connection)->table('finance_diamond_stream')->where('user_id', $val['user_id'])->where('diamond_value', '<', 0)->selectRaw('sum(diamond_value) as diamondAll, user_id')->get();
            $diamondAll = objToArray($diamondAll);
            $item['chongzhiAll'] = empty($chongzhiAll[0]['diamondNum']) ? '0' : $chongzhiAll[0]['diamondNum']/100;
            $item['diamondAll'] = empty($diamondAll[0]['diamondAll']) ? '0' : $diamondAll[0]['diamondAll'];
            
            $data[] = $item;
        }

        $headers = [
            '邀请码',
            '用户UUID', 
            '用户昵称',
            '注册时间',
            '邀请人UUID',
            '邀请人昵称',
            '登录IP',
            '充值金额',
            '钻石消费'
        ];

        $fileName = '邀请明细_'.date('YmdHis').'.xlsx';
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        $sheet = $objPHPExcel->getActiveSheet();

        // 写入表头
        foreach($headers as $k => $v){
            $sheet->setCellValue(chr(65 + $k).'1', $v);
        }

        // 写入数据
        $i = 2;
        foreach($data as $item){
            $sheet->setCellValue('A'.$i, $item['invite_code']);
            $sheet->setCellValue('B'.$i, $item['user_uuid']);
            $sheet->setCellValue('C'.$i, $item['user_nickname']); 
            $sheet->setCellValue('D'.$i, $item['reg_time']);
            $sheet->setCellValue('E'.$i, $item['invite_uuid']);
            $sheet->setCellValue('F'.$i, $item['invite_nickname']);
            $sheet->setCellValue('G'.$i, $item['loginIp']);
            $sheet->setCellValue('H'.$i, $item['chongzhiAll']);
            $sheet->setCellValue('I'.$i, $item['diamondAll']);
            $i++;
        }

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        // 设置header
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$fileName.'"');
        header('Cache-Control: max-age=0');

        // 直接输出到浏览器
        $objWriter->save('php://output');
        exit;

    }
    

    //解绑邀请人
    public function changeMoveInviteCode(Request $request)
    {
        $invite_user_id = $request->input('invite_uuid');
        $data['invite_uid_new'] = 0;
        $query = DB::connection($this->connection)->table($this->userTable)->where('uuid',$invite_user_id)->update($data);
        return $query;
    }
    public function changeBindInviteCode(Request $request)
    {
        $user_id = $request->input('user_uuid');
        $inviteCode = $request->post('invite_code', '');// 邀请码（所属邀请人）
        $inviteUserId = 0;
//         todo 检测邀请码是否存在（将code转成user_id值）
        if (!empty($inviteCode)) {
            $inviteUserData = $this->getUserByCode($inviteCode);
            if (empty($inviteUserData)) {
                return null;
            }
        }else{
            return null;
        }
            $inviteUserId = $inviteUserData['user_id'];
        $data['invite_uid_new'] = $inviteUserId;
        $query = DB::connection($this->connection)->table($this->userTable)->where('uuid',$user_id)->update($data);
        return $query;
    }

    /**
     * 通过邀请Code获取用户
     * @param $code
     * @return mixed|null
     */
    public function getUserByCode($code){

        // 关系数据库读取
        $users = DB::connection($this->connection)->table($this->userTable)
            ->where("code", "=", strval($code))
            ->first();
        $result = self::objToArray($users);

        if(!empty($result)){
            if(!empty($result['union_vest']) && $result['union_vest_switch'] ==1){
                $result['nickname'] = $result['union_vest'].'·'.$result['nickname'];
            }
            if(!empty($result['province']) && !empty($result['city'])){
                $result['home'] = $result['province'].'#'.$result['city'];
            }else{
                $result['home'] = '';
            }
        }
        // 设置缓存
        if(empty($result)){
            return null;
        }
        return $result;
    }



}
